package com.github.framework.webmvc.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.RandomAccessFile;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: springv2
 * @description: 对应一个页面
 * @author: Pop
 * @create: 2021-06-26 22:59
 **/
public class View {

    private File viewFile;

    public View(File viewFile)
    {
        this.viewFile = viewFile;
    }

    public void render(Map<String,?> model, HttpServletRequest req, HttpServletResponse resp) throws  Exception {
        StringBuilder page = new StringBuilder();

        RandomAccessFile ra = new RandomAccessFile(this.viewFile,"r");
        String line = null;
        while(null!=(line=ra.readLine()))
        {
            line = new String(line.getBytes("iso-8859-1"),"utf-8");
            // 大小写忽略   大小写不敏感                 [^\}]+ 只要不以}结尾的都算
            Pattern pattern = Pattern.compile("￥\\{[^\\}]+\\}",Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(line);
            while(matcher.find())
            {
                String paramName = matcher.group();
                //拿到的是￥{XXXX}这样的内容，将前后缀替换为空
                paramName = paramName.replaceAll("￥\\{|\\}","");
                Object paramValue = model.get(paramName);
                // html一些元素进行特殊处理。将匹配到的值替换到
                line = matcher.replaceFirst(makeStringForRegExp(paramValue.toString()));
                //下一次匹配。一行也许有多个参数
                matcher = pattern.matcher(line);
            }
            page.append(line);
        }
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().write(page.toString());
    }

    //处理特殊字符 html里面的一些特殊字符
    public static String makeStringForRegExp(String str) {
        return str.replace("\\", "\\\\").replace("*", "\\*")
                .replace("+", "\\+").replace("|", "\\|")
                .replace("{", "\\{").replace("}", "\\}")
                .replace("(", "\\(").replace(")", "\\)")
                .replace("^", "\\^").replace("$", "\\$")
                .replace("[", "\\[").replace("]", "\\]")
                .replace("?", "\\?").replace(",", "\\,")
                .replace(".", "\\.").replace("&", "\\&");
    }
}
